package com.banciyuan.bcywebview.biz.groupdetail;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.myinterface.ActionInterface;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.biz.post.succ.PostSuccActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.DetailType;

/**
 * Created by squall on 2015/8/25.
 */
public class EditGroupActivity extends BaseActivity implements View.OnClickListener {

    private AutoCompleteTextView title_et;
    private EditText tag_et;
    private FlowView tag_select;
    private FlowView tag_recommend;
    private Button save;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private TextView tv_skip;
    private final int GO_COMPLATE = 55;
    private List<String> slist = new ArrayList<>();
    private List<String> tlist = new ArrayList<>();
    private List<String> pathList = new ArrayList<>();
    private String name;
    private String content;
    private TextView tag_add;
    private RequestQueue queue;
    private AutoComplateAdapter adapter;
    private LayoutInflater inflater;
    private MyProgressDialog mDialog;
    private String work;
    private ActionInterface actionInterface;
    private boolean is_post = false;
    private String defaultTag = "";
    private String defaultWork = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_group);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        initData();
        findhotTag();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        pathList = (List<String>) intent.getSerializableExtra("pathList");
        name = intent.getStringExtra("name");
        content = intent.getStringExtra("content");
        queue = VolleyQueue.getRquest(this);
        inflater = LayoutInflater.from(EditGroupActivity.this);
        defaultTag = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        defaultWork = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        actionInterface = new ActionInterface() {
            @Override
            public void onNetError(String result) {
                MyToast.show(EditGroupActivity.this, result);
            }
        };
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.label_topic_add));
        mActionbarHelper.addItemOneText(getString(R.string.post));
        tv_skip = (TextView) findViewById(R.id.base_action_bar_home_text_item);
    }

    @Override
    protected void initUi() {
        title_et = (AutoCompleteTextView) findViewById(R.id.edit_group_autotv);
        tag_et = (EditText) findViewById(R.id.tag_add_et);
        tag_select = (FlowView) findViewById(R.id.add_tag_lv);
        tag_recommend = (FlowView) findViewById(R.id.add_retag_lv);
        save = (Button) findViewById(R.id.edit_group_commit);
        tag_add = (TextView) findViewById(R.id.tag_group_add);
        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();
        title_et.setText(defaultWork);
        if (!TextUtils.isEmpty(defaultTag)) {
            tag_et.setText(defaultTag);
            addTagFun(tag_et);
        }
    }

    @Override
    protected void initAction() {

        title_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            final IGetAutoComplate iGetAutoComplate = new IGetAutoComplate() {
                @Override
                public void getComplateList(String s, boolean show) {
                    dealJson(s);
                }
            };

            @Override
            public void afterTextChanged(Editable editable) {
                if (!title_et.isPerformingCompletion()) {
                    if (!TextUtils.isEmpty(editable.toString())) {
                        getCompleteWork(editable, iGetAutoComplate);
                    }
                    if (TextUtils.isEmpty(editable.toString())) {
                        title_et.dismissDropDown();
                    }
                }
            }
        });

        tag_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_DONE) {
                    addTagFun(tag_add);
                }
                return true;
            }
        });
        tag_add.setOnClickListener(onLabelClick);
        tv_skip.setOnClickListener(this);


    }

    private void getCompleteWork(Editable editable, IGetAutoComplate iGetAutoComplate) {
        String url = HttpUtils.BASE_URL + CoreApi.getGetcorelist();
        AutoComplateHelper autoHelper = new AutoComplateHelper(this, iGetAutoComplate, "");
        autoHelper.findServerTitle(editable, true, url);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.base_action_bar_home_text_item:
                if (TextUtils.isEmpty(title_et.getText()) && tlist.isEmpty()) {
                    MyToast.show(this, getString(R.string.no_work_tags));
                } else {
                    mDialog.show();
                    saveGroup();
                }
                break;
        }
    }

    private void dealJson(String s) {
        if (StatusCodeUtils.dealStatusCode(s, this)) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                adapter = new AutoComplateAdapter(slist, this, title_et.getText().toString());
                title_et.setAdapter(adapter);

            } catch (Exception e) {
            }
        }
        if (!EditGroupActivity.this.isFinishing()) {
            title_et.showDropDown();
        }
    }

    private void findhotTag() {
        String url = HttpUtils.BASE_URL + GroupApi.getRecommendtags();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditGroupActivity.this)) {
                    addTag(s);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                actionInterface.onNetError(getString(R.string.label_recommend_fail));
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, null);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, onSucc, errorProxy);
        queue.add(stringRequestParam);
    }

    View.OnClickListener onLabelClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addTagFun(view);
        }
    };

    private void addTagFun(View view) {
        String label = "";
        if (view.getId() == R.id.tag_group_add) {
            label = tag_et.getText().toString();
            if (TextUtils.isEmpty(label)) {
                MyToast.show(EditGroupActivity.this, getString(R.string.label_shoudnot_benull));
                return;
            }
        } else {
            label = ((TextView) view).getText().toString();
        }
        if (tlist.contains(label)) {
            MyToast.show(EditGroupActivity.this, getString(R.string.label_mutli_disable));
            return;
        } else {
            if (tlist.size() < 5) {
                tlist.add(label);
            } else {
                MyToast.show(EditGroupActivity.this, getString(R.string.label_five_limit));
                return;
            }
        }
        if (tag_select.getVisibility() == View.GONE) {
            tag_select.setVisibility(View.VISIBLE);
        }

        View viewcancel = inflater.inflate(R.layout.tag_blue_cancel, null);
        TextView textview = (TextView) viewcancel.findViewById(R.id.single_tag_cancel);
        textview.setText(label);
        tag_select.addView(viewcancel);
        viewcancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tag_select.removeView(view);
                TextView cancel_label = (TextView) view.findViewById(R.id.single_tag_cancel);
                tlist.remove(cancel_label.getText().toString());
                if (tag_select.getChildCount() == 0) {
                    tag_select.setVisibility(View.GONE);
                }
            }
        });

        tag_et.setText("");
    }

    private void addTag(String s) {
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONArray jsonArray = jsonObject.getJSONArray("data");

            for (int i = 0; i < jsonArray.length(); i++) {
                View view = inflater.inflate(R.layout.tag_nomargin_blue, null);
                TextView textview = (TextView) view.findViewById(R.id.single_tag);
                textview.setText(jsonArray.getString(i));
                textview.setOnClickListener(onLabelClick);
                tag_recommend.addView(view);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void saveGroup() {
        work = title_et.getText().toString();
        if (!pathList.isEmpty()) {
            addGroupInfo(pathList);
        } else {
            addGroupInfo(new ArrayList<String>());
        }
    }

    private void addGroupInfo(List<String> pathList) {
        if (is_post) return;
        is_post = true;
        Response.Listener<String> onSuccAdd = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditGroupActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        Intent intent = new Intent();
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, jsonObject.getString("data"));
                        intent.setClass(EditGroupActivity.this, NewTeamDetailActivity.class);
                        startActivityForResult(intent, GO_COMPLATE);

                        Intent succ = new Intent();
                        succ.setClass(EditGroupActivity.this, PostSuccActivity.class);
                        DetailType detailType = new DetailType();
                        detailType.setGid(jsonObject.getString("data"));
                        detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_GROUP_TEAM);
                        succ.putExtra("detailtype", detailType);
                        startActivity(succ);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                is_post = false;
                if (!EditGroupActivity.this.isFinishing()) {
                    mDialog.dismiss();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                is_post = false;
                if (!EditGroupActivity.this.isFinishing()) {
                    mDialog.dismiss();
                }
                actionInterface.onNetError(getString(R.string.creat_topic_fail));
            }
        };

        String url = HttpUtils.BASE_URL + GroupApi.getAddgroup();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(EditGroupActivity.this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.NAME, name));
        paramsList.add(new BcyPair(HttpUtils.GROUP_INTRO, content));

        if (!TextUtils.isEmpty(work)) {
            paramsList.add(new BcyPair(HttpUtils.GROUP_WORK, work));
        }
        if (!tlist.isEmpty()) {
            JSONArray jsonarray = new JSONArray(tlist);
            paramsList.add(new BcyPair(HttpUtils.TAG_NAMES, jsonarray.toString()));
        }
        if (!pathList.isEmpty()) {
            JSONArray jsonarray = new JSONArray(pathList);
            paramsList.add(new BcyPair(HttpUtils.GROUP_PATHS, jsonarray.toString()));
        }
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam request = new StringRequestParam(Request.Method.POST, url, map, onSuccAdd, onError);
        request.setRetryPolicy(new DefaultRetryPolicy(60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GO_COMPLATE) {
            setResult(999, new Intent());
            finish();
        }
    }

}
